bitmasks brute force constructive algorithms greedy implementation math *1800

Please click on ads to support us..

Python Code:

def path(x, y):
    ma = max(x, y)
    mi = min(x, y)

    u = [ma]
    v = [mi]

    while u[-1] != v[-1]:
        if ma > mi:
            ma //= 2
            u.append(ma)
        else:
            mi //= 2
            v.append(mi)

    return v + u[::-1][1:]

def solve():
    n = int(input())
    a = [int(i) for i in input().split()]
    d = []

    for i in range(n):
        if a[i] != -1:
            d.append(i)

    if not d:
        for i in range(0, n, 2):
            a[i] = 1
            if i + 1 != n:
                a[i + 1] = 2
        return a
        
    for i in range(d[0] - 1, -1, -1):
        if a[i + 1] == 1:
            a[i] = a[i + 1] * 2
        else:
            a[i] = a[i + 1] // 2

    for i in range(d[-1] + 1, len(a)):
        if a[i - 1] == 1:
            a[i] = a[i - 1] * 2
        else:
            a[i] = a[i - 1] // 2

    for i in range(0, len(d) - 1):
        p = path(a[d[i]], a[d[i + 1]])

        if d[i + 1] - d[i] + 1 < len(p):
            return [-1]

        if (d[i + 1] - d[i] + 1 - len(p)) % 2:
            return [-1]

        if p[0] != a[d[i]]:
            p.reverse()

        p = p[1:-1]

        for j in range(d[i] + 1, d[i + 1]):
            if j - d[i] - 1 >= len(p):
                if j == 1:
                    if a[j - 1] == 1:
                        a[j] = a[j - 1] * 2
                    else:
                        a[j] = a[j - 1] // 2
                else:
                    a[j] = a[j - 2]
            else:
                a[j] = p[j - d[i] - 1]

    return a

for _ in range(int(input())):
    print(*solve())


Comments

Submit
0 Comments
More Questions

873B - Balanced Substring
1401D - Maximum Distributed Tree
1716C - Robot in a Hallway
1688B - Patchouli's Magical Talisman
99A - Help Far Away Kingdom
622B - The Time
1688C - Manipulating History
1169D - Good Triple
1675B - Make It Increasing
588A - Duff and Meat
1541B - Pleasant Pairs
1626B - Minor Reduction
1680A - Minimums and Maximums
1713A - Traveling Salesman Problem
1713B - Optimal Reduction
1710A - Color the Picture
1686B - Odd Subarrays
251A - Points on Line
427C - Checkposts
1159A - A pile of stones
508A - Pasha and Pixels
912A - Tricky Alchemy
1249A - Yet Another Dividing into Teams
1713C - Build Permutation
1699A - The Third Three Number Problem
1617B - GCD Problem
841A - Generous Kefa
1690B - Array Decrements
1692C - Where's the Bishop
104A - Blackjack